const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const chalk = require('chalk')
const addVueConfig = require('./addConfig')
const addModule = require('./addModule')

const inputName = function () {
  let question = [
    {
      name: 'name',
      type: 'input',
      message: '请输入目录名称',
      validate(val) {
        if (val === '') {
          return '目录名称不能为空'
        } else if (/[\u4e00-\u9fa5]/g.test(val)) {
          return '目录名称不能包含中文'
        } else {
          return true
        }
      }
    },
    {
      name: 'title',
      type: 'input',
      message: '请输入title',
      validate(val) {
        if (val === '') {
          return 'title名称不能为空'
        } else {
          return true
        }
      }
    }
  ]
  inquirer.prompt(question).then(answers => {
    dirDetector(answers.name, answers.title)
  }).catch(err => {
    console.log(chalk.red(err))
  })
}

// 验证目录是否存在
const dirDetector = function (name, title) {
  if (fs.existsSync(path.resolve(`./src/modules/${ name }`))) {
    inquirer.prompt([
      {
        type: 'confirm',
        message: '目录已存在，是否继续？',
        name: 'ok'
      }
    ]).then(answers => {
      if (answers.ok) {
        createPage(name, title)
      } else {
        inputName()
      }
    }).catch(err => {
      console.log(chalk.red(err))
    })

  } else {
    createPage(name, title)
  }
}

// 创建目录
const createPage = (name, title) => {
  addVueConfig(name, title)
  addModule(name, title)
}

inputName()